package net.sf.log4jdbc;

import java.sql.Connection;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import net.sf.log4jdbc.ConnectionSpy;
import net.sf.log4jdbc.DriverSpy;
import net.sf.log4jdbc.SpyLogFactory;
import net.sf.log4jdbc.RdbmsSpecifics;

public class DataSourceSpyInterceptor implements MethodInterceptor {

	private RdbmsSpecifics rdbmsSpecifics = null;

	private boolean sqlTimingErrorThresholdEnabled = false;

	private boolean SqlTimingWarnThresholdEnabled = false;
	private long sqlTimingErrorThresholdMsec;
	private long SqlTimingWarnThresholdMsec;

	private RdbmsSpecifics getRdbmsSpecifics(Connection conn) {
		if (this.rdbmsSpecifics == null) {
			this.rdbmsSpecifics = DriverSpy.getRdbmsSpecifics(conn);
		}
		return this.rdbmsSpecifics;
	}

	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object result = invocation.proceed();
		if ((SpyLogFactory.getSpyLogDelegator().isJdbcLoggingEnabled()) && (result instanceof Connection)) {
			Connection conn = (Connection) result;
			DriverSpy.SqlTimingErrorThresholdEnabled = this.sqlTimingErrorThresholdEnabled;
			DriverSpy.SqlTimingErrorThresholdMsec = this.sqlTimingErrorThresholdMsec;
			DriverSpy.SqlTimingWarnThresholdEnabled = this.SqlTimingWarnThresholdEnabled;
			DriverSpy.SqlTimingWarnThresholdMsec = this.SqlTimingWarnThresholdMsec;
			return new ConnectionSpy(conn, getRdbmsSpecifics(conn));
		}

		return result;
	}

	public boolean isSqlTimingErrorThresholdEnabled() {
		return this.sqlTimingErrorThresholdEnabled;
	}

	public void setSqlTimingErrorThresholdEnabled(boolean sqlTimingErrorThresholdEnabled) {
		this.sqlTimingErrorThresholdEnabled = sqlTimingErrorThresholdEnabled;
	}

	public long getSqlTimingErrorThresholdMsec() {
		return this.sqlTimingErrorThresholdMsec;
	}

	public void setSqlTimingErrorThresholdMsec(long sqlTimingErrorThresholdMsec) {
		this.sqlTimingErrorThresholdMsec = sqlTimingErrorThresholdMsec;
	}

	public boolean isSqlTimingWarnThresholdEnabled() {
		return this.SqlTimingWarnThresholdEnabled;
	}

	public void setSqlTimingWarnThresholdEnabled(boolean sqlTimingWarnThresholdEnabled) {
		this.SqlTimingWarnThresholdEnabled = sqlTimingWarnThresholdEnabled;
	}

	public long getSqlTimingWarnThresholdMsec() {
		return this.SqlTimingWarnThresholdMsec;
	}

	public void setSqlTimingWarnThresholdMsec(long sqlTimingWarnThresholdMsec) {
		this.SqlTimingWarnThresholdMsec = sqlTimingWarnThresholdMsec;
	}

}
